<template>
  <div class="chat-container">
    <!-- 聊天记录 -->
    <div class="chat-messages" ref="messageContainer">
      <div v-for="(msg, index) in messages" :key="index" 
           :class="['message', msg.fromUserId === userId ? 'message-right' : 'message-left']">
        <div class="message-content">{{ msg.content }}</div>
        <div class="message-time">{{ formatTime(msg.sendTime) }}</div>
      </div>
    </div>
    
    <!-- 输入框 -->
    <div class="chat-input">
      <el-input
        v-model="inputMessage"
        placeholder="请输入消息..."
        @keyup.enter="sendMessage"
      >
        <template #append>
          <el-button @click="sendMessage">发送</el-button>
        </template>
      </el-input>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { formatDate } from '@/utils/date'

const props = defineProps({
  userId: {
    type: String,
    required: true
  }
})

const messages = ref([])
const inputMessage = ref('')
const ws = ref(null)
const messageContainer = ref(null)

// 初始化WebSocket连接
const initWebSocket = () => {
  const wsUrl = `ws://localhost/websocket/customerService/${props.userId}`
  ws.value = new WebSocket(wsUrl)
  
  ws.value.onopen = () => {
    console.log('WebSocket连接成功')
  }
  
  ws.value.onmessage = (e) => {
    const message = JSON.parse(e.data)
    messages.value.push(message)
    scrollToBottom()
  }
  
  ws.value.onerror = (e) => {
    console.error('WebSocket错误：', e)
  }
  
  ws.value.onclose = () => {
    console.log('WebSocket连接关闭')
  }
}

// 发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim()) return
  
  const message = {
    fromUserId: props.userId,
    toUserId: 'admin', // 发送给客服
    content: inputMessage.value,
    sendTime: new Date(),
    messageType: 1
  }
  
  ws.value.send(JSON.stringify(message))
  messages.value.push(message)
  inputMessage.value = ''
  scrollToBottom()
}

// 滚动到底部
const scrollToBottom = () => {
  setTimeout(() => {
    const container = messageContainer.value
    container.scrollTop = container.scrollHeight
  }, 50)
}

// 格式化时间
const formatTime = (time) => {
  return formatDate(new Date(time), 'yyyy-MM-dd HH:mm:ss')
}

onMounted(() => {
  initWebSocket()
})

onUnmounted(() => {
  if (ws.value) {
    ws.value.close()
  }
})
</script>

<style scoped>
.chat-container {
  height: 500px;
  display: flex;
  flex-direction: column;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.message {
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
}

.message-left {
  align-items: flex-start;
}

.message-right {
  align-items: flex-end;
}

.message-content {
  max-width: 70%;
  padding: 10px;
  border-radius: 4px;
  background-color: #f4f4f5;
  word-break: break-all;
}

.message-right .message-content {
  background-color: #409eff;
  color: white;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.chat-input {
  padding: 10px;
  border-top: 1px solid #dcdfe6;
}
</style> 